//
//  EMSelectItemViewController.swift
//  Hyphenate-Demo-Swift
//
//  Created by 杜洁鹏 on 2017/11/29.
//  Copyright © 2017年 杜洁鹏. All rights reserved.
//

import UIKit
import Hyphenate

//import Toast_Swift


protocol SelectItemViewControllerDelegate {
    func didSelected()
}

class InviteGroupMemberListController: EMSelectItemViewController {
    
 
    var contactList = [String]()
    var groups: [String: String] = [:]

    func getGroupMembers(groupId: String) {
        EMClient.shared().groupManager.getGroupMemberListFromServer(withId: groupId, cursor: "", pageSize: 999) { (result, error) in
            if result?.list != nil {
                
                self.groups.removeValue(forKey: groupId)
                
                for username in result!.list {
                    
                    self.contactList.append(username as! String)
                }
                
                
                EMClient.shared().groupManager.getGroupSpecificationFromServer(withId: groupId) { (result, error) in
                    if result?.memberList != nil {
                        
                        self.groups.removeValue(forKey: groupId)
                        
                        if(!self.contactList.contains(result!.owner)){
                            
                            self.contactList.append(result!.owner)
                           
                        }
                         self.reloadData()
                    }
                }
                
            }
            
            
        }
        
       
    }
    
    override func sortContacts(contactList: Array<String>) {
        if selectedAry == nil {
            selectedAry = Array<IEMUserModel>()
        }
        self.contactList.forEach { (hyphenateId) in
                if(hyphenateId != EMClient.shared()?.currentUsername){
                    selectedAry!.append(EMUserModel.createWithHyphenateId(hyphenateId: hyphenateId) as! IEMUserModel)
                }
        };
        
        super.sortContacts(contactList: contactList)
        
        updateSelectedCount()
        
    }
    
    func reloadData(){
        
        contactList.removeAll { (username) -> Bool in
            return username == EMClient.shared().currentUsername
        }
        
        sortContacts(contactList: self.contactList)
        weak var weakSelf = self
        DispatchQueue.main.async {
            weakSelf?.tableView.reloadData()
            weakSelf?.refreshControl?.endRefreshing()
        }
    }
    
    override func setupDataSource() {
        getGroupMembers(groupId: groupId)
    }
  
}
